#!/bin/sh
###
 # @Author: 烟雨
 # @Date: 2025-07-28 19:50:45
 # @LastEditors: 烟雨
 # @LastEditTime: 2025-07-28 19:50:45
 #
 # Copyright (c) 2025 by 烟雨, All Rights Reserved.
###

import requests
import hashlib
import time,os
from datetime import datetime
from loguru import logger
from concurrent.futures import ThreadPoolExecutor, as_completed
from urllib.parse import unquote

'''
# cron: 58 59 8,11,14 26,27,28 * * 
# new Env("顺丰会员日兑换")
环境变量：SFSY_QD  多账户换行
也可以填写url到 129行的 token中，多账户换行！
'''

# 自定义日志格式
logger.remove()  # 移除默认控制台输出
logger.add(
    sink=lambda msg: print(msg, end=""),
    format="{time:YYYY-MM-DD HH:mm:ss.SSS} | {level:<5} | {message}",
    level="INFO"
)

class Run:
    def __init__(self, index):
        self.headers = {
            'Host': 'mcs-mimp-web.sf-express.com',
            'upgrade-insecure-requests': '1',
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36 NetType/WIFI MicroMessenger/7.0.20.1781(0x6700143B) WindowsWechat(0x63090551) XWEB/6945 Flue',
            'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
            'sec-fetch-site': 'none',
            'sec-fetch-mode': 'navigate',
            'sec-fetch-user': '?1',
            'sec-fetch-dest': 'document',
            'accept-language': 'zh-CN,zh',
            'platform': 'MINI_PROGRAM',
        }
        self.s = requests.session()
        self.mobile = '未知'  # 初始化mobile属性
        self.login_res = self.login(index)

    def getSign(self):
        timestamp = str(int(time.time() * 1000))
        token = 'wwesldfs29aniversaryvdld29'
        sysCode = 'MCS-MIMP-CORE'
        data = f'token={token}&timestamp={timestamp}&sysCode={sysCode}'
        signature = hashlib.md5(data.encode()).hexdigest()
        self.headers.update({
            'sysCode': sysCode,
            'timestamp': timestamp,
            'signature': signature
        })

    def do_request(self, url, data={}, req_type='post'):
        self.getSign()
        try:
            if req_type.lower() == 'get':
                response = self.s.get(url, headers=self.headers)
            elif req_type.lower() == 'post':
                response = self.s.post(url, headers=self.headers, json=data)
            else:
                raise ValueError('Invalid req_type: %s' % req_type)
            return response.json()
        except Exception as e:
            logger.error(f'[{self.mobile}] 请求失败: {e}')
            return None

    def login(self, sfurl):
        try:
            # 先解码URL
            decoded_url = unquote(sfurl)
            ress = self.s.get(decoded_url, headers=self.headers)
            self.user_id = self.s.cookies.get_dict().get('_login_user_id_', '')
            self.phone = self.s.cookies.get_dict().get('_login_mobile_', '')
            if self.phone:
                self.mobile = self.phone[:3] + "*" * 4 + self.phone[7:]
                logger.info(f'【{self.mobile}】登录成功')
                return True
            else:
                logger.error(f'获取用户信息失败 - URL: {sfurl}')
                return False
        except Exception as e:
            logger.error(f'登录异常: {e}')
            return False

    def exchangehyr(self):
        if not self.login_res:
            logger.error(f'{self.mobile} 登录失败，跳过兑换')
            return
        try:
            now = datetime.now()
            if now.hour == 8:
                data = {"roundTime": "09:00"}
            elif now.hour == 11:
                data = {"roundTime": "12:00"}
            elif now.hour == 14:
                data = {"roundTime": "15:00"}
            else:
                logger.error(f'{self.mobile} 当前时间不在兑换时段，跳过')
                return
            for _ in range(2):
                urldh = "https://mcs-mimp-web.sf-express.com/mcs-mimp/commonPost/~memberNonactivity~memberDayFreeService~freeCouponPurchase"
                res = self.do_request(urldh, data)
                if res and res.get('success'):
                    logger.success(f'{self.mobile}: 兑换成功 - {res}')
                    break
                elif res:
                    logger.info(f'{self.mobile}: 兑换结果 - {res}')
        except Exception as e:
            logger.error(f'{self.mobile}: 执行错误 - {e}')

# ------------------------ 多线程并发部分 ------------------------

def process_token(index):
    r = Run(index)
    r.exchangehyr()

if __name__ == '__main__':
    # token = """https://mcs-mimp-web.sf-express.com/xxxxxxxxxxxxxxxxxxxxxxxxxx
# https://mcs-mimp-web.sf-express.com/xxxxxxxxxxxxxxxxxxxxxxxxxx"""
    token = """"""
    if token == "":
        token = os.getenv('SFSY_QD')

    if not token:
        logger.error("未找到token或环境变量SFSY_QD")
        exit(1)
        
    tokens = [t.strip() for t in token.strip().split('\n') if t.strip()]
    logger.info(f"\n>>>>>>>>>> 共获取到 {len(tokens)} 个账号 <<<<<<<<<<\n")

    with ThreadPoolExecutor(max_workers=10) as executor:  # 可调整并发数
        futures = [executor.submit(process_token, token_url) for token_url in tokens]

        for future in as_completed(futures):
            try:
                future.result()
            except Exception as e:
                logger.error(f"任务执行异常: {e}")